<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-23 11:04:47
 * @LastEditTime: 2023-02-15 20:14:29
 * @Description: 添加集合
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="true"
    :maskClosable="true"
    :destroyOnClose="true"
    :visible="visible"
    :width="$store.getters.isMobile ? 300 : 600"
    @close="handleClose"
    :body-style="{
      paddingBottom: '80px',
    }"
  >
    <a-form layout="vertical">
      <a-form-item label="集合名称" v-bind="validateInfos.collection_name">
        <a-input
          placeholder="请输入集合名称"
          v-model:value="modelRef.collection_name"
        />
      </a-form-item>
      <a-form-item v-bind="validateInfos.village_type">
        <template #label>
          <span>项目类型</span>
          <text-tip tips="“集合”是同一种项目类型的楼宇的集合" />
        </template>
        <a-select
          :options="showVillageTypeList"
          placeholder="请选择项目类型"
          v-model:value="modelRef.village_type"
          @change="handleVillageTypeChange"
        />
      </a-form-item>
      <a-form-item label="选择楼宇" v-bind="validateInfos.collection_build">
        <ChooseHousingResources
          checkType="build"
          :attachDpt="0"
          :userChecked="0"
          :villageType="modelRef.village_type"
          :defaultChecked="defaultChecked"
          @request="$utils.commonRequest"
          @getResult="getBuildingList"
          @getTree="getTreeList"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="handleClose">关闭</a-button>
      <a-button type="primary" @click.prevent="handleSuccess">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  ref,
  watch,
  reactive,
  toRaw,
  nextTick,
} from "vue";
import request from "../../../../common/utils/request";
import { Form, message } from "ant-design-vue";
import { ChooseHousingResources, TextTip } from "bl-common-vue3";
const useForm = Form.useForm;

export default defineComponent({
  name: "BucketsAdd",
  components: { ChooseHousingResources, TextTip },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const title = computed(() => (props.id ? "编辑集合" : "添加集合"));
    const modelRef = reactive({
      collection_name: "",
      village_type: undefined,
      collection_build: [],
      build: {},
    });
    const rulesRef = reactive({
      collection_name: [{ required: true, message: "请填写集合名称" }],
      collection_build: [{ required: true, message: "请选择楼宇" }],
      village_type: [{ required: true, message: "请选择项目类型" }],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const handleVillageTypeChange = () => {
      modelRef.collection_build = [];
    };

    const getBuildingList = (detail) => {
      const { villageList, buildList } = detail;
      let ids = [];
      villageList.forEach((v) => {
        if (v.children && v.children.length) {
          v.children.forEach((b) => {
            ids.push(b.id);
          });
        }
      });
      buildList.forEach((b) => {
        ids.push(b.id);
      });
      modelRef.collection_build = ids;
    };

    const villageTypeList = ref([]);
    const showVillageTypeList = ref([]);

    const getVillageTypes = () => {
      return new Promise((resolve) => {
        if (villageTypeList.value.length) {
          resolve();
        } else {
          request.get("/village", "/village/type/list").then((res) => {
            villageTypeList.value = res.list.map((item) => ({
              label: item.name,
              value: item.alias,
            }));
            resolve();
          });
        }
      });
    };

    const getTreeList = (detail) => {
      if (showVillageTypeList.value.length) return;
      let types = [];
      detail.oList.forEach((item) => {
        if (item.type && !types.includes(item.type)) {
          types.push(item.type);
        }
      });
      getVillageTypes().then(() => {
        showVillageTypeList.value = villageTypeList.value.filter((item) =>
          types.includes(item.value)
        );
      });
    };

    const handleClose = () => {
      context.emit("cancel");
    };
    const handleSuccess = () => {
      setTimeout(() => {
        validate().then(() => {
          let params = { ...toRaw(modelRef), needMsg: true };
          params.build = {
            buildId: params.collection_build,
          };
          params.collection_build = JSON.stringify(params.collection_build);
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success");
          };
          if (props.id) {
            params.id = props.id;
            request
              .put("/org", "/build/collection", params)
              .then((res) => success(res));
          } else {
            request
              .post("/org", "/build/collection", params)
              .then((res) => success(res));
          }
        });
      }, 0);
    };

    const defaultChecked = reactive({
      buildList: [],
    });
    const getDetail = () => {
      if (props.id) {
        request
          .get("/org", "/build/collectionDetail", {
            id: props.id,
          })
          .then((res) => {
            const { data } = res;
            modelRef.collection_name = data.collection_name;
            modelRef.village_type = data.village_type;
            modelRef.collection_build = data.collection_build || [];
            defaultChecked.buildList = modelRef.collection_build.map((id) => ({
              id,
            }));
          });
      }
    };
    const init = () => {
      getDetail();
    };

    const resetData = () => {
      resetFields();
      defaultChecked.buildList = [];
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetData();
        }
      }
    );

    return {
      title,
      showVillageTypeList,
      getTreeList,
      modelRef,
      validateInfos,
      handleClose,
      handleSuccess,
      getBuildingList,
      handleVillageTypeChange,
      defaultChecked,
    };
  },
});
</script>

<style lang="less" scoped>
.building-list {
  .building-item {
    width: 100%;
    background: #f1f1f1;
    height: 30px;
    display: flex;
    align-items: center;
    margin: 10px 0;
    padding: 10px;
    cursor: pointer;
    justify-content: space-between;
  }
  .active {
    background: @primary-color-bg;
    color: @primary-color;
  }
}
</style>
